import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { logger } from '../../utils/logger';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES, VALIDATION_ERROR_CODES } from '../../utils/errorCodes';
import { deleteFile, getFileUrl } from '../../middleware/upload';

export class ContentController extends BaseController {
  // ==================== 冷知识管理 ====================

  // 获取冷知识列表
  async getTrivia(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 20, artistId, isActive } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      // 构建查询条件
      const where: any = {};
      
      if (artistId) {
        where.artistId = parseInt(artistId as string);
      }
      
      if (isActive !== undefined) {
        where.isActive = isActive === 'true';
      }

      // 查询冷知识列表
      const [trivia, total] = await Promise.all([
        prisma.trivia.findMany({
          where,
          skip,
          take: limitNum,
          orderBy: { createdAt: 'desc' },
          include: {
            artist: {
              select: {
                id: true,
                name: true,
                avatar: true
              }
            }
          }
        }),
        prisma.trivia.count({ where })
      ]);

      ResponseUtils.paginated(res, trivia, total, pageNum, limitNum, '获取冷知识列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取冷知识详情
  async getTriviaById(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const triviaId = parseInt(id);

      if (isNaN(triviaId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的冷知识ID');
        return;
      }

      const trivia = await prisma.trivia.findUnique({
        where: { id: triviaId },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        }
      });

      if (!trivia) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '冷知识不存在');
        return;
      }

      ResponseUtils.success(res, { funFact: trivia }, '获取冷知识详情成功');
    } catch (error) {
      next(error);
    }
  }

  // 创建冷知识
  async createTrivia(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { title, content, artistId, isActive } = req.body;

      // 验证必填字段
      if (!title || !content) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '标题和内容不能为空');
        return;
      }

      // 检查艺人是否存在
      if (artistId) {
        const artist = await prisma.artist.findUnique({
          where: { id: parseInt(artistId) }
        });

        if (!artist) {
          ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '艺人不存在');
          return;
        }
      }

      const trivia = await prisma.trivia.create({
        data: {
          title,
          content,
          artistId: artistId ? parseInt(artistId) : null,
          isActive: isActive !== undefined ? isActive : true
        },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        }
      });

      logger.info(`冷知识创建成功: ${trivia.title} (ID: ${trivia.id})`);
      ResponseUtils.created(res, trivia, '创建冷知识成功');
    } catch (error) {
      next(error);
    }
  }

  // 更新冷知识
  async updateTrivia(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const triviaId = parseInt(id);
      const { title, content, artistId, isActive } = req.body;

      if (isNaN(triviaId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的冷知识ID');
        return;
      }

      // 检查冷知识是否存在
      const existingTrivia = await prisma.trivia.findUnique({
        where: { id: triviaId }
      });

      if (!existingTrivia) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '冷知识不存在');
        return;
      }

      // 检查艺人是否存在
      if (artistId) {
        const artist = await prisma.artist.findUnique({
          where: { id: parseInt(artistId) }
        });

        if (!artist) {
          ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '艺人不存在');
          return;
        }
      }

      const updatedTrivia = await prisma.trivia.update({
        where: { id: triviaId },
        data: {
          title,
          content,
          artistId: artistId ? parseInt(artistId) : null,
          isActive
        },
        include: {
          artist: {
            select: {
              id: true,
              name: true,
              avatar: true
            }
          }
        }
      });

      logger.info(`冷知识更新成功: ${updatedTrivia.title} (ID: ${updatedTrivia.id})`);
      ResponseUtils.updated(res, updatedTrivia, '更新冷知识成功');
    } catch (error) {
      next(error);
    }
  }

  // 删除冷知识
  async deleteTrivia(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const triviaId = parseInt(id);

      if (isNaN(triviaId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的冷知识ID');
        return;
      }

      // 检查冷知识是否存在
      const trivia = await prisma.trivia.findUnique({
        where: { id: triviaId }
      });

      if (!trivia) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '冷知识不存在');
        return;
      }

      await prisma.trivia.delete({
        where: { id: triviaId }
      });

      logger.info(`冷知识删除成功: ${trivia.title} (ID: ${triviaId})`);
      ResponseUtils.deleted(res, '删除冷知识成功');
    } catch (error) {
      next(error);
    }
  }

  // ==================== 徽章管理 ====================

  // 获取徽章列表
  async getBadges(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 20, type } = req.query;
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      // 构建查询条件
      const where: any = {};
      
      if (type) {
        where.type = type;
      }

      // 查询徽章列表
      const [badges, total] = await Promise.all([
        prisma.badge.findMany({
          where,
          skip,
          take: limitNum,
          orderBy: { createdAt: 'desc' },
          include: {
            _count: {
              select: {
                userBadges: true
              }
            }
          }
        }),
        prisma.badge.count({ where })
      ]);

      // 格式化响应数据
      const formattedBadges = badges.map((badge: any) => ({
        ...badge,
        earnedCount: badge._count.userBadges
      }));

      ResponseUtils.paginated(res, formattedBadges, total, pageNum, limitNum, '获取徽章列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 创建徽章
  async createBadge(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { name, description, icon, type, conditionType, conditionValue } = req.body;

      // 验证必填字段
      if (!name) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '徽章名称不能为空');
        return;
      }

      // 检查徽章名称是否已存在
      const existingBadge = await prisma.badge.findFirst({
        where: { name }
      });

      if (existingBadge) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.BADGE_ALREADY_EXISTS, '徽章名称已存在');
        return;
      }

      const badge = await prisma.badge.create({
        data: {
          name,
          description,
          icon,
          type,
          conditionType,
          conditionValue: conditionValue ? parseInt(conditionValue) : null
        }
      });

      logger.info(`徽章创建成功: ${badge.name} (ID: ${badge.id})`);
      ResponseUtils.created(res, badge, '创建徽章成功');
    } catch (error) {
      next(error);
    }
  }

  // 更新徽章
  async updateBadge(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const badgeId = parseInt(id);
      const { name, description, icon, type, conditionType, conditionValue } = req.body;

      if (isNaN(badgeId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的徽章ID');
        return;
      }

      // 检查徽章是否存在
      const existingBadge = await prisma.badge.findUnique({
        where: { id: badgeId }
      });

      if (!existingBadge) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.BADGE_NOT_FOUND, '徽章不存在');
        return;
      }

      // 如果更新名称，检查是否与其他徽章重名
      if (name && name !== existingBadge.name) {
        const nameConflict = await prisma.badge.findFirst({
          where: {
            name,
            id: { not: badgeId }
          }
        });

        if (nameConflict) {
          ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.BADGE_ALREADY_EXISTS, '徽章名称已存在');
          return;
        }
      }

      const updatedBadge = await prisma.badge.update({
        where: { id: badgeId },
        data: {
          name,
          description,
          icon,
          type,
          conditionType,
          conditionValue: conditionValue ? parseInt(conditionValue) : null
        }
      });

      logger.info(`徽章更新成功: ${updatedBadge.name} (ID: ${updatedBadge.id})`);
      ResponseUtils.updated(res, updatedBadge, '更新徽章成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取徽章详情
  async getBadgeById(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const badgeId = parseInt(id);

      if (isNaN(badgeId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的徽章ID');
        return;
      }

      const badge = await prisma.badge.findUnique({
        where: { id: badgeId },
        include: {
          _count: {
            select: {
              userBadges: true
            }
          }
        }
      });

      if (!badge) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.BADGE_NOT_FOUND, '徽章不存在');
        return;
      }

      ResponseUtils.success(res, { badge }, '获取徽章详情成功');
    } catch (error) {
      next(error);
    }
  }

  // 删除徽章
  async deleteBadge(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const badgeId = parseInt(id);

      if (isNaN(badgeId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的徽章ID');
        return;
      }

      // 检查徽章是否存在
      const badge = await prisma.badge.findUnique({
        where: { id: badgeId },
        include: {
          _count: {
            select: {
              userBadges: true
            }
          }
        }
      });

      if (!badge) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.BADGE_NOT_FOUND, '徽章不存在');
        return;
      }

      // 检查是否有关联数据
      if (badge._count.userBadges > 0) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.OPERATION_NOT_ALLOWED, '该徽章已被用户获得，无法删除');
        return;
      }

      // 删除徽章图标文件
      if (badge.icon) {
        const filename = badge.icon.split('/').pop();
        if (filename) {
          deleteFile(filename, 'badgeIcon');
        }
      }

      await prisma.badge.delete({
        where: { id: badgeId }
      });

      logger.info(`徽章删除成功: ${badge.name} (ID: ${badgeId})`);
      ResponseUtils.deleted(res, '删除徽章成功');
    } catch (error) {
      next(error);
    }
  }

  // 上传徽章图标
  async uploadBadgeIcon(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const badgeId = parseInt(id);

      if (isNaN(badgeId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的徽章ID');
        return;
      }

      if (!req.file) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.REQUIRED_FIELD_MISSING, '请选择要上传的图标文件');
        return;
      }

      // 检查徽章是否存在
      const existingBadge = await prisma.badge.findUnique({
        where: { id: badgeId }
      });

      if (!existingBadge) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.BADGE_NOT_FOUND, '徽章不存在');
        return;
      }

      // 删除旧图标文件
      if (existingBadge.icon) {
        const oldFilename = existingBadge.icon.split('/').pop();
        if (oldFilename) {
          deleteFile(oldFilename, 'badgeIcon');
        }
      }

      // 更新徽章图标URL
      const iconUrl = getFileUrl(req.file.filename, 'badgeIcon');
      const updatedBadge = await prisma.badge.update({
        where: { id: badgeId },
        data: { icon: iconUrl }
      });

      logger.info(`徽章图标上传成功: ${updatedBadge.name} (ID: ${badgeId})`);
      ResponseUtils.success(res, { 
        badge: updatedBadge,
        iconUrl: iconUrl
      }, '徽章图标上传成功');
    } catch (error) {
      next(error);
    }
  }

  // 删除徽章图标
  async deleteBadgeIcon(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const badgeId = parseInt(id);

      if (isNaN(badgeId)) {
        ResponseUtils.sendError(res, VALIDATION_ERROR_CODES.FIELD_TYPE_ERROR, '无效的徽章ID');
        return;
      }

      // 检查徽章是否存在
      const existingBadge = await prisma.badge.findUnique({
        where: { id: badgeId }
      });

      if (!existingBadge) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.BADGE_NOT_FOUND, '徽章不存在');
        return;
      }

      // 检查是否有图标
      if (!existingBadge.icon) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.RESOURCE_NOT_FOUND, '徽章没有图标');
        return;
      }

      // 删除图标文件
      const filename = existingBadge.icon.split('/').pop();
      if (filename) {
        deleteFile(filename, 'badgeIcon');
      }

      // 更新徽章，清空图标URL
      const updatedBadge = await prisma.badge.update({
        where: { id: badgeId },
        data: { icon: null }
      });

      logger.info(`徽章图标删除成功: ${updatedBadge.name} (ID: ${badgeId})`);
      ResponseUtils.success(res, updatedBadge, '徽章图标删除成功');
    } catch (error) {
      next(error);
    }
  }
} 